package com.hrbxlh.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.ChapterActionImpl;
import com.hrbxlh.actionImpl.CourseActionImpl;
import com.hrbxlh.actionImpl.MyCourseActionImpl;
import com.hrbxlh.actionImpl.RelationActionImpl;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.DateUtil;
import com.hrbxlh.util.SessionValues;

/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：MyCourse.java
* Description：我的课程action类
* History：
* Date           Author               Desc
* 2017.4.5		  xzx                 建立
* -------------------------------------------------------
*/

@Controller
public class MyCourseAction {

	@Autowired
	@Qualifier("myCourseActionImpl")
	private MyCourseActionImpl myCourseActionImpl;
	
	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;
	
	@Autowired
	@Qualifier("chapterActionImpl")
	private ChapterActionImpl chapterActionImpl;
	
	@Autowired
	@Qualifier("relationActionImpl")
	private RelationActionImpl relationActionImpl;
	
	
	/**
	 * @description 跳转到我的课程页面（教师、学生）
	 * @param request
	 * @param response
	 * @return  跳转到我的课程页面
	 * @throws IOException
	 */
	@RequestMapping(value = "/skipMyCourse", method = RequestMethod.GET)
	public ModelAndView skipMyCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MyCourseAction.class.getName());
		try {
			//获取登录人角色信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"roleId","stuorteaId"}, request);
			resultMap = sessionValues;
			//获取我的课程信息
			List<Map<String, Object>> courseList = myCourseActionImpl.getMyCourse(resultMap);
			resultMap.put("courseList", courseList);
			//获取课程表信息
			List<Map<String, Object>> courseTabList = myCourseActionImpl.getCouseTab(resultMap);
			resultMap.put("courseTabList", courseTabList);
			//获取当前星期全部日期从周一到周日
			List<String> dateList = DateUtil.dateToWeek(new Date());
			resultMap.put("dateList", dateList);
			resultMap.put("roleId", resultMap.get("roleId"));
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//我的课程页面名称
			pageName = "pc/myCourse";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转我的课程页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**
	 * @description 获取上一周或下一周的课程表
	 * @param request
	 * @param response
	 * 	//Map<String, Object> map = new HashMap<String ,Object>();
		//map.put("date", "2017-04-08");
		//jsonStr = mapper.writeValueAsString(map);
	 * @return  课表信息
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getCourseTabAjax", method = RequestMethod.POST)
	public void  getCourseTabAjax (HttpServletResponse response, HttpServletRequest request, String jsonStr) throws IOException {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MyCourseAction.class.getName());
		try { 
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//获取登录人角色信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"roleId","stuorteaId"}, request);
			resultMap = sessionValues;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//获取当前星期全部日期从周一到周日
			List<String> dateList = DateUtil.dateToWeek(sdf.parse((String)paramMap.get("date")));
			resultMap.put("dateList", dateList);
			//获取课表信息
			List<Map<String, Object>> courseTabList = myCourseActionImpl.getTabList(resultMap);
			resultMap.put("courseTabList", courseTabList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询课程表出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
	/**
	 * @description 在我的课程点击某课程进入的课程详情页面 (老师学生走一个action)
	 * @param request
	 * @param response
	 * 	//Map<String, Object> map = new HashMap<String ,Object>();
		//map.put("courseId", 18);
		//jsonStr = mapper.writeValueAsString(map);
	 * @param jsonStr 需要课程id
	 * @return  
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipCourseStudyDetail", method = RequestMethod.GET)
	public ModelAndView skipCourseStudyDetail(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MyCourseAction.class.getName());
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//获取登录人角色信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"roleId","stuorteaId"}, request);
			sessionValues.put("courseId", paramMap.get("courseId"));
			//获取登录人学习了的章节信息
			List<Map<String, Object>> studyList = courseActionImpl.getMyStudyChapterList(sessionValues);
			resultMap.put("studyList", studyList);
			//获取课程详细信息
			Map<String, Object> courseDetail = courseActionImpl.getCourseDetail(sessionValues,request); 
			resultMap.put("courseDetail", courseDetail);
			//获取学习了几个章节的进度信息
			Map<String, Object> studyProcess = courseActionImpl.getMyStudyProcess(sessionValues);
			resultMap.put("process", studyProcess.get("process"));
			//获取课程章节信息
			List<Map<String, Object>> chapterList = chapterActionImpl.getCourseChapter(sessionValues);
			resultMap.put("chapterList", chapterList);
			//获取文件前缀
			String[] keysArray = {"server_address", "project_name"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/course/";
			resultMap.put("url", url);
			resultMap.put("roleId", sessionValues.get("roleId"));
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//存入进页面的标识，没有就是正常1是提交作业成功进来的
			resultMap.put("pageMark", paramMap.get("pageMark"));
			//如果是学生，需要查询这个课，这个学生所在班级的老师id
			Map<String, Object> teacherIdMap = relationActionImpl.getMyTeacherByCourseId(sessionValues);
			resultMap.put("teacherId", teacherIdMap.get("stuorteaId"));
			//课程学习页面名称
			pageName = "pc/stuCourseStudy";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转课程学习页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**
	 * @description 进入虚拟机环境的action 
	 * 参数为课程id　章节id
	 * 带值：虚拟机信息、课件信息、文件前缀
	 * @param request
	 * @param response
	 * @return 
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipTestEnvirunmentList", method = RequestMethod.GET)
	public ModelAndView skipTestEnvirunmentList(String jsonStr,HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MyCourseAction.class.getName());
		try {
			//获取参数值 
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//通过课程，章节，查询课程课件信息
			Map<String, Object> chapterMsg = courseActionImpl.getChapterByCourseId(paramMap);
			resultMap.put("chapterMsg", chapterMsg);
			//文件前缀
			//获取文件前缀
			String[] keysArray = {"server_address", "project_name"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/course/";
			resultMap.put("url", url);
			//获取登录人角色信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"roleId","stuorteaId"}, request);
			//获取登录人的虚机信息
			List<Map<String, Object>> virtualAddressList = myCourseActionImpl.getMyvirtualAddress(sessionValues);
			resultMap.put("virtualAddressList", virtualAddressList);
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//获取这个学生这个课，这个章节的试验评价
			Map<String, Object> testAssign = myCourseActionImpl.getMyTestAssign(paramMap, request);
			resultMap.put("testAssign", testAssign);
			//视频名称
			resultMap.put("videoName", paramMap.get("videoName"));
			//页面名称
			pageName = "pc/testEnvironment";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转测试页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**
	 * @description 清空进度信息(教师)
	 * @param request  
	 * @param response
	 * //Map<String, Object> map = new HashMap<String ,Object>();
		//map.put("courseId", 18);
		//jsonStr = mapper.writeValueAsString(map);
	 * @param 课程id
	 * @return  
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/emptyProcess", method = RequestMethod.POST)
	public void  emptyProcess (HttpServletResponse response, HttpServletRequest request, String jsonStr) throws IOException {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MyCourseAction.class.getName());
		try { 
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//获取登录人角色信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request);
			sessionValues.put("courseId", paramMap.get("courseId"));
			//清空进度信息
			boolean result = courseActionImpl.emptyProcess(sessionValues);
			String resultMark = (result) ? "success" : "fail";
			resultMap.put("result", resultMark);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("清除进度出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
	/**
	 * @description 添加进度信息（教师与学生）
	 * @param request  
	 * @param response
	 * @param 课程id
	 * //Map<String, Object> map = new HashMap<String ,Object>();
		//map.put("courseId", 18);
		//map.put("chapterId", 18);
		//jsonStr = mapper.writeValueAsString(map);
	 * @return  
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addProcess", method = RequestMethod.POST)
	public void  addProcess (HttpServletResponse response, HttpServletRequest request, String jsonStr) throws IOException {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MyCourseAction.class.getName());
		try { 
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//获取登录人角色信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request);
			sessionValues.put("courseId", paramMap.get("courseId"));
			sessionValues.put("chapterId", paramMap.get("chapterId"));
			//添加进度信息
			boolean result = courseActionImpl.addProcess(sessionValues);
			String resultMark = (result) ? "success" : "fail";
			resultMap.put("result", resultMark);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加进度信息出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
}